/*
 * Copyright 2024 LinQingYing. and contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * The use of this source code is governed by the Apache License 2.0,
 * which allows users to freely use, modify, and distribute the code,
 * provided they adhere to the terms of the license.
 *
 * The software is provided "as-is", and the authors are not responsible for
 * any damages or issues arising from its use.
 *
 */

package com.linqingying.cangjie.types.expressions

import com.intellij.util.containers.CollectionFactory
import com.linqingying.cangjie.config.LanguageVersionSettings
import com.linqingying.cangjie.descriptors.impl.LocalVariableDescriptor
import com.linqingying.cangjie.psi.CjLoopExpression
import com.linqingying.cangjie.psi.CjTryExpression
import com.linqingying.cangjie.resolve.calls.smartcasts.DataFlowInfo
import com.linqingying.cangjie.resolve.calls.smartcasts.DataFlowValue
import com.linqingying.cangjie.resolve.calls.smartcasts.IdentifierInfo
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet

/**
 * The purpose of this class is to find all variable assignments
 * **before** loop analysis
 */
class PreliminaryLoopVisitor private constructor() : AssignedVariablesSearcher() {

  fun clearDataFlowInfoForAssignedLocalVariables(
    dataFlowInfo: DataFlowInfo,
    languageVersionSettings: LanguageVersionSettings,
  ): DataFlowInfo {
    var resultFlowInfo = dataFlowInfo
    val nonTrivialValues = CollectionFactory.createSmallMemoryFootprintSet< DataFlowValue >().apply {
      addAll(dataFlowInfo.completeNullabilityInfo.iterator().map { it._1 })
      addAll(dataFlowInfo.completeTypeInfo.iterator().map { it._1 })
    }
    val valueSetToClear = LinkedHashSet<DataFlowValue>()
    for (value in nonTrivialValues) {
      // Only stable variables are under interest here
      val identifierInfo = value.identifierInfo
      if (value.kind == DataFlowValue.Kind.STABLE_VARIABLE && identifierInfo is IdentifierInfo.Variable) {
        val variableDescriptor = identifierInfo.variable
        if (variableDescriptor is LocalVariableDescriptor && hasWriters(variableDescriptor)) {
          valueSetToClear.add(value)
        }
      }
    }
    for (valueToClear in valueSetToClear) {
      resultFlowInfo = resultFlowInfo.clearValueInfo(valueToClear, languageVersionSettings)
    }
    return resultFlowInfo
  }

  companion object {

    @JvmStatic
    fun visitLoop(loopExpression: CjLoopExpression): PreliminaryLoopVisitor {
      val visitor = PreliminaryLoopVisitor()
      loopExpression.accept(visitor, null)
      return visitor
    }

    @JvmStatic
    fun visitTryBlock(tryExpression: CjTryExpression): PreliminaryLoopVisitor {
      val visitor = PreliminaryLoopVisitor()
      tryExpression.tryBlock.accept(visitor, null)
      return visitor
    }

    @JvmStatic
    fun visitCatchBlocks(tryExpression: CjTryExpression): PreliminaryLoopVisitor =
      visitCatchBlocks(tryExpression, tryExpression.catchClauses.map { true })

    @JvmStatic
    fun visitCatchBlocks(tryExpression: CjTryExpression, isBlockShouldBeVisited: List<Boolean>): PreliminaryLoopVisitor {
      val catchClauses = tryExpression.catchClauses
      assert(catchClauses.size == isBlockShouldBeVisited.size)
      val visitor = PreliminaryLoopVisitor()
      catchClauses.zip(isBlockShouldBeVisited)
        .filter { (_, shouldBeVisited) -> shouldBeVisited }
        .forEach { (clause, _) -> clause.catchBody?.accept(visitor, null) }
      return visitor
    }
  }
}
